package com.nmgydy.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

public class Formater {

	/**
	 * 编码设置
	 */
	public static final String CHARACTER_ENCODING = "UTF-8";
	/**
	 * 系统默认编码
	 */
	public static final String CHARACTER_ENCODING_DEFAULT = "ISO-8859-1";

	public static final String REGEX_SCRIPT = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
	public static final String REGEX_STYLE = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
	public static final String REGEX_HTML = "<[^>]+>"; // 定义HTML标签的正则表达式

	/**
	 * 生成hql判等子句
	 *
	 * @param key
	 * @param value
	 * @param params
	 * @return
	 */
	public static String hqlEqual(String key, String value, Map<String, Object> params) {
		String hql = "";
		if (Formater.isNotEmpty(value)) {
			hql = " and a." + key + "=:" + key;
			params.put(key, value);
		}
		return hql;
	}

	/**
	 * 生成hql Like子句
	 *
	 * @param key
	 * @param value
	 * @param params
	 * @return
	 */
	public static String hqlLike(String key, String value, Map<String, Object> params) {
		String hql = "";
		if (Formater.isNotEmpty(value)) {
			hql = " and a." + key + " like :" + key;
			params.put(key, "%" + value + "%");
		}
		return hql;
	}

	/**
	 * 是否数字
	 *
	 * @param str
	 *            字符串
	 * @return 是为true
	 */
	public static boolean isInteger(String str) {
		if (str == null || str.isEmpty()) {
			return false;
		}
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	/**
	 * 以文字像素和字数截取字符串
	 *
	 * @param str
	 *            字符串
	 * @param fontWidth
	 *            文字像素大小
	 * @param fontCount
	 *            截取的文字数量
	 * @return
	 */
	public static String getReturnWidthLeft(String str, int fontWidth, int fontCount) {

		str = str.replaceAll("[\\r\\n|\\n|\\r]", "");

		str = quotes(str, false);

		String rtn = "";
		int tempWidth = 0;
		for (int i = 0; i < str.length(); i++) {
			if (isChinese(str.substring(i, i + 1))) {
				tempWidth += fontWidth;
			} else {
				tempWidth += fontWidth / 2;
			}
			if (tempWidth > fontWidth * fontCount) {
				break;
			} else {
				rtn += str.substring(i, i + 1);
			}
		}

		rtn = quotes(rtn, true);

		return rtn;
	}

	/**
	 * 以字节截取字符串
	 *
	 * @param str
	 *            字符串
	 * @param byteNumber
	 *            截取的字节数
	 * @return
	 */
	public static String getReturnLeft(String str, int byteNumber) {

		str = quotes(str, false);

		String rtn = "";
		byte[] bt = null;
		if (CHARACTER_ENCODING == null) {
			bt = str.getBytes();
		} else {
			try {
				bt = str.getBytes(CHARACTER_ENCODING);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (byteNumber >= bt.length) {
			rtn = str;
		} else {
			if (byteNumber < 1) {
				rtn = str;
			} else {
				String tempStr = "";
				for (int i = 0; i < str.length(); i++) {
					tempStr += str.substring(i, i + 1);
					try {
						byte[] tempByte = tempStr.getBytes(CHARACTER_ENCODING);
						if (tempByte.length > byteNumber) {
							break;
						} else {
							rtn += str.substring(i, i + 1);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		rtn = quotes(rtn, true);

		return rtn;
	}

	/**
	 * 以字节数截取字符串 当前编码
	 *
	 * @param str
	 *            字符串
	 * @param byteNumber
	 *            截取的字节数
	 * @param characterEncoding
	 *            当前编码
	 * @return
	 */
	public static String getReturnLeft(String str, int byteNumber, String characterEncoding) {
		return getReturnLeft(str, byteNumber);
	}

	/**
	 * 是否中文 单个字符
	 *
	 * @param c
	 *            字符
	 * @return 是为true
	 */
	private static final boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * 是否包含中文
	 *
	 * @param strName
	 *            字符串
	 * @return 是为true
	 */
	public static final boolean isChinese(String strName) {
		char[] ch = strName.toCharArray();
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if (isChinese(c)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 是否中文编码
	 *
	 * @param chineseStr
	 *            字符串
	 * @return 是为true
	 */
	public static final boolean isChineseCharacter(String chineseStr) {
		char[] charArray = chineseStr.toCharArray();
		for (int i = 0; i < charArray.length; i++) {
			if ((charArray[i] >= 0x4e00) && (charArray[i] <= 0x9fbb)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 是否不空不null
	 *
	 * @param value
	 *            字符串
	 * @return 不为空、不为null为true
	 */
	public static final boolean isNotEmpty(String value) {
		boolean rtn = false;
		value = trim(value);
		if (value != null && !value.isEmpty()) {
			rtn = true;
		}
		return rtn;
	}

	/**
	 * 去除两边空格
	 *
	 * @param value
	 *            字符串
	 * @return 不为空、不为null为""
	 */
	public static final String trim(Object value) {
		String rtn = "";
		if (value != null) {
			rtn = value.toString().trim();
		}
		return rtn;
	}

	/**
	 * 格式化日期 将yyyyMMdd格式的日期转换为yyyy-MM-dd格式
	 *
	 * @param dateStr
	 *            日期字符串
	 * @return 新格式日期
	 */
	public static String formatStrDate(String dateStr) {
		if (dateStr == null || dateStr.isEmpty()) {
			return "";
		}
		String rtn = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		try {
			Date date = sdf.parse(dateStr);
			rtn = new SimpleDateFormat("yyyy-MM-dd").format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return rtn;
	}

	/**
	 * 格式化日期 将指定格式的日期转换为新格式
	 *
	 * @param dateStr
	 *            日期字符串
	 * @param oldStr
	 *            旧格式
	 * @param newStr
	 *            新格式
	 * @return 新格式日期
	 */
	public static String formatStrDate(String dateStr, String oldStr, String newStr) {
		if (dateStr == null || dateStr.isEmpty()) {
			return "";
		}
		String rtn = null;
		SimpleDateFormat sdf = new SimpleDateFormat(oldStr);
		try {
			Date date = sdf.parse(dateStr);
			rtn = new SimpleDateFormat(newStr).format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return rtn;
	}

	/**
	 * 字符日期串转
	 *
	 * @param date
	 *            日期
	 * @param formatStr
	 *            格式 "yyyy-MM-dd HH:mm:ss"
	 * @return 日期
	 */
	public static Date getDateByStr(String dateStr, String formatStr) {
		// TimeZone tz = TimeZone.getTimeZone("ETC/GMT+8");
		// TimeZone.setDefault(tz);
		DateFormat dd = new SimpleDateFormat(formatStr);
		Date date = null;
		try {
			date = dd.parse(dateStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 字符日期串转
	 *
	 * @param date
	 *            日期
	 * @param formatStr
	 *            格式 "yyyy-MM-dd HH:mm:ss"
	 * @return 字符串日期
	 */
	public static String getStrByDate(Date date, String formatStr) {
		// TimeZone tz = TimeZone.getTimeZone("ETC/GMT+8");
		// TimeZone.setDefault(tz);
		SimpleDateFormat df = new SimpleDateFormat(formatStr);
		String result = df.format(date);
		return result;
	}

	/**
	 * 获取日期的星期 0-----6表示星期一 到星期日
	 * **/
	public static int getWeekBy(int year, int month, int day) {
		// TimeZone tz = TimeZone.getTimeZone("ETC/GMT+8");
		// TimeZone.setDefault(tz);
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, day);
		if (cal.get(Calendar.DAY_OF_WEEK) - 2 < 0) {
			return 6;
		} else {
			return cal.get(Calendar.DAY_OF_WEEK) - 2;
		}
	}

	/**
	 * 获取日期的星期 0-----6表示星期一 到星期日
	 * **/
	public static int getWeekByDate(Date date) {
		// TimeZone tz = TimeZone.getTimeZone("ETC/GMT+8");
		// TimeZone.setDefault(tz);
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		if (cal.get(Calendar.DAY_OF_WEEK) - 2 < 0) {
			return 6;
		} else {
			return cal.get(Calendar.DAY_OF_WEEK) - 2;
		}
	}

	/**
	 * 获取日期的星期 0-----6表示星期一 到星期日
	 * **/
	public static int getWeekByStr(String date, String formatStr) {
		return getWeekByDate(getDateByStr(date, formatStr));
	}

	/**
	 * 获取日期的星期 0-----6表示 "一" 到 "日"
	 * **/
	public static String getWeekNameBydata(Date date) {
		int week = getWeekByDate(date);
		String result = "";
		switch (week) {
			case 0:
				result = "一";
				break;
			case 1:
				result = "二";
				break;
			case 2:
				result = "三";
				break;
			case 3:
				result = "四";
				break;
			case 4:
				result = "五";
				break;
			case 5:
				result = "六";
				break;
			case 6:
				result = "日";
				break;
		}
		return result;
	}

	/**
	 * 获取加减后的日期
	 *
	 * @param date
	 * @param number
	 * @return
	 */
	public static Date getDateAdd(Date date, int number) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_YEAR, number);
		return calendar.getTime();
	}

	/**
	 * 获取加减后的时间
	 *
	 * @param date
	 * @param number
	 *            分钟
	 * @return
	 */
	public static Date getTimeAdd(Date date, int number) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MINUTE, number);
		return calendar.getTime();
	}

	/**
	 * 获取加减后的时间
	 *
	 * @param date
	 * @param number
	 *            天
	 * @return
	 */
	public static Date getTimeAddDay(Date date, int number) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, number);
		return calendar.getTime();
	}

	/**
	 * 将double类型的数字转换为2个小数点（0.00）的字符串
	 *
	 * @param lStr
	 *            原数字
	 * @return 新格式字符串
	 */
	public static String formatDecimal(double lStr) {
		return formatDecimal(lStr, 2);
	}

	/**
	 * 将double类型的数字转换为指定小数点（0.*）的字符串
	 *
	 * @param lStr
	 *            原数字
	 * @param number
	 *            小数点后位数
	 * @return 新格式字符串
	 */
	public static String formatDecimal(double lStr, int number) {
		String rtn = null;
		BigDecimal bd = new BigDecimal(Double.toString(lStr));
		if (number > 0) {
			String fStr = "0.";
			for (int i = 0; i < number; i++) {
				fStr += "0";
			}
			rtn = new DecimalFormat(fStr).format(bd.setScale(number, BigDecimal.ROUND_HALF_UP).doubleValue());
		} else {
			rtn = bd.setScale(number, BigDecimal.ROUND_HALF_UP).toString();
		}
		return rtn;
	}

	/**
	 * 将字符串类型的数字转换为2个小数点（0.00）的字符串
	 *
	 * @param lStr
	 *            原数字
	 * @return 新格式字符串
	 */
	public static String formatDecimal(String lStr) {
		return formatDecimal(lStr, 2);
	}

	/**
	 * 将字符串类型的数字转换为指定小数点（0.*）的字符串
	 *
	 * @param lStr
	 *            原数字
	 * @param number
	 *            小数点后位数
	 * @return 新格式字符串
	 */
	public static String formatDecimal(String lStr, int number) {
		String rtn = null;
		BigDecimal bd = new BigDecimal(lStr);
		if (number > 0) {
			String fStr = "0.";
			for (int i = 0; i < number; i++) {
				fStr += "0";
			}
			rtn = new DecimalFormat(fStr).format(bd.setScale(number, BigDecimal.ROUND_HALF_UP).doubleValue());
		} else {
			rtn = bd.setScale(number, BigDecimal.ROUND_HALF_UP).toString();
		}
		return rtn;
	}

	/**
	 * 将double类型数字四舍五入处理后转换为整数字符串
	 *
	 * @param lStr
	 *            原数字
	 * @return 新整数字符串
	 */
	public static String formatInt(double lStr) {
		return String.valueOf((int) Math.round(lStr));
	}

	/**
	 * “除”计算（有效位15，最大万亿级别）
	 *
	 * @param amtStrLeft
	 * @param amtStrRight
	 * @return
	 */
	public static BigDecimal decimalDivide(BigDecimal amtStrLeft, BigDecimal amtStrRight) {
		if (amtStrRight == null || amtStrRight.doubleValue() == 0.00) {
			return new BigDecimal("0.00");
		}
		MathContext mc = new MathContext(15, RoundingMode.HALF_UP);
		return amtStrLeft.divide(amtStrRight, mc);
	}

	/**
	 * URLEncoder编码
	 *
	 * @param str
	 *            字符串
	 * @return 编码后的字符串
	 */
	public static String encode(String str) {
		String rtn = "";
		if (isNotEmpty(str)) {
			try {
				rtn = URLEncoder.encode(str, Formater.CHARACTER_ENCODING);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return rtn;
	}

	/**
	 * URLDecoder解码
	 *
	 * @param str
	 *            字符串
	 * @return 解码后的字符串
	 */
	public static String decode(String str) {
		String rtn = "";
		if (isNotEmpty(str)) {
			try {
				rtn = URLDecoder.decode(str, Formater.CHARACTER_ENCODING);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return rtn;
	}

	/**
	 * 获得编码转换后的结果
	 *
	 * @param old
	 * @return
	 */
	public static String getNewString(String old) {
		String rtn = null;
		try {
			rtn = new String(old.getBytes(CHARACTER_ENCODING_DEFAULT), CHARACTER_ENCODING);
		} catch (UnsupportedEncodingException e) {
			//
			e.printStackTrace();
		}
		return rtn;
	}

	/**
	 * 将系统编码的字符串转换为当前编码的字符串
	 *
	 * @param value
	 *            字符串
	 * @return 新字符串
	 */
	public static String character(String value) {
		String rtn = "";
		if (Formater.CHARACTER_ENCODING.equals(CHARACTER_ENCODING_DEFAULT)) {
			rtn = value;
		} else {
			try {
				rtn = new String(value.getBytes(CHARACTER_ENCODING_DEFAULT), Formater.CHARACTER_ENCODING);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return rtn;
	}

	/**
	 * 将数字字符串转换为double类型
	 *
	 * @param value
	 *            数字字符串
	 * @return double数字
	 */
	public static double toDouble(String value) {
		double rtn = 0;
		if (!isNotEmpty(value))
			return rtn;
		try {
			rtn = Double.parseDouble(value);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rtn;
	}

	/**
	 * HTML编码
	 *
	 * @param text
	 *            字符串
	 * @return html编码后的字符串
	 */
	public static String htmlEnCode(String text) {
		if (text == null)
			return "";
		StringBuffer results = null;
		char[] orig = null;
		int beg = 0, len = text.length();
		for (int i = 0; i < len; ++i) {
			char c = text.charAt(i);
			switch (c) {
				case 0:
				case '&':
				case '<':
				case '>':
				case '\r':
				case '\n':
				case '"':
					if (results == null) {
						orig = text.toCharArray();
						results = new StringBuffer(len + 10);
					}
					if (i > beg)
						results.append(orig, beg, i - beg);
					beg = i + 1;
					switch (c) {
						default: // case 0:
							continue;
						case '&':
							results.append("&amp;");
							break;
						case '<':
							results.append("&gt;");
							break;
						case '>':
							results.append("&lt;");
							break;
						case '\r':
						case '\n':
							results.append("<br/>");
							break;
						case '"':
							results.append("\"");
							break;
					}
					break;
			}
		}
		if (results == null)
			return text;
		results.append(orig, beg, len - beg);
		return results.toString();
	}

	/**
	 * 将表单中的html尖括号进行处理
	 *
	 * @param str
	 *            表单内容字符串
	 * @return 处理后的内容字符串
	 */
	public static String formEncode(String str) {
		String rtn = "";
		if (isNotEmpty(str)) {
			str = quotes(str, true);
			// str = str.replaceAll("<[^>]*>", "");
			str = str.replace("<", "&lt;");
			str = str.replace(">", "&gt;");
			rtn = str;
		}
		return rtn;
	}

	/**
	 * 转移字符处理
	 *
	 * @param str
	 *            字符串
	 * @param right
	 *            true转成标准html字符，否反方向转换
	 * @return 处理后的字符串
	 */
	public static String quotes(String str, boolean right) {
		if (right) {
			str = str.replaceAll("\"", "&quot;");
			str = str.replaceAll("\'", "&#39;");
		} else {
			str = str.replaceAll("&quot;", "\"");
			str = str.replaceAll("&#39;", "\'");
		}
		return str;
	}

	/**
	 * JavaScript &符号处理
	 *
	 * @param str
	 *            字符串
	 * @return 处理后的字符串
	 */
	public static String jsEncode(String str) {
		String rtn = "";
		if (isNotEmpty(str)) {
			str = str.replaceAll("&", "\\\\&");
			rtn = str;
		}
		return rtn;
	}

	/**
	 * 获取标示符左边文本
	 *
	 * @param str
	 *            文本
	 * @param tag
	 *            标示符
	 * @return
	 */
	public static String getLeftByTag(String str, String tag) {
		return str.substring(0, str.indexOf(tag));
	}

	/**
	 * 获取标示符右边文本
	 *
	 * @param str
	 *            文本
	 * @param tag
	 *            标示符
	 * @return
	 */
	public static String getRightByTag(String str, String tag) {
		return str.substring(str.indexOf(tag), str.length() - str.substring(0, str.indexOf(tag)).length());
	}

	/**
	 * 获取标示符中间文本
	 *
	 * @param str
	 *            文本
	 * @param leftTag
	 *            左侧标示符
	 * @param rightTag
	 *            右侧标示符
	 * @return
	 */
	public static String getBetweenByTag(String str, String leftTag, String rightTag) {
		int i = str.indexOf(leftTag) + leftTag.length();
		return str.substring(i, str.indexOf(rightTag, i));
	}

	/**
	 * 获取标示符中间文本 同样的标示符之间
	 *
	 * @param str
	 *            文本
	 * @param tag
	 *            两侧标示符
	 * @return
	 */
	public static String getBetweenByTag(String str, String tag) {
		int i = str.indexOf(tag) + tag.length();
		return str.substring(i, str.indexOf(tag, i));
	}

	/**
	 * 清除HTML标记
	 *
	 * @param htmlStr
	 * @return
	 */
	public static String removeHTML(String htmlStr) {
		Pattern p_script = Pattern.compile(REGEX_SCRIPT, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern.compile(REGEX_STYLE, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_html = Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签

		return htmlStr.trim(); // 返回文本字符串
	}

	/**
	 * 获取固定长度随机数
	 *
	 * @param length
	 *            长度
	 */
	public static int getRandom(int length) {
		Random rand = new Random();
		return (int) (rand.nextFloat() * (Math.pow(10, length)));
	}

	/**
	 * 获取指定范围内的随机数
	 *
	 * @param min
	 *            最小数字
	 * @param max
	 *            最大数字
	 * @return
	 */
	public static int getRandomByMin2Max(int min, int max) {
		if (min < 0 || min > max) {
			System.out.println("getRandomByMin2Max参数错误");
			min = 0;
			max = 0;
		}
		return (int) (Math.random() * (max + 1 - min) + min);
	}

	/**
	 * request的parameter转换为map
	 *
	 * @param requestMap
	 *            request.getParameterMap()方法
	 * @return
	 */
	public static Map<String, String> requestToMap(Map<String, String[]> requestMap) {
		Map<String, String> map = new HashMap<String, String>();
		for (String key : requestMap.keySet()) {
			String value = "";
			for (String parameter : requestMap.get(key)) {
				parameter = formatSql(parameter);

				// 特殊处理，验证排序参数 - 开始
				if ("sortField".equals(key) && parameter != null && !"".equals(parameter)) {
					// 验证字段名
					String regex = "^[a-zA-Z][\u4e00-\u9fa5_a-zA-Z0-9]+$";
					if (!parameter.matches(regex)) {
						parameter = "";
					}
				}
				if ("sortOrder".equals(key) && parameter != null && !"".equals(parameter)) {
					if (!"desc".equals(parameter) && !"asc".equals(parameter)) {
						parameter = "";
					}
				}
				// 特殊处理，验证排序参数 - 结束

				if (value == "") {
					value = parameter;
				} else {
					value += "," + parameter;
				}
			}
			map.put(key, value);
		}
		return map;
	}

	/**
	 * 简单过滤sql注入
	 *
	 * @param value
	 *            输入参数
	 * @return
	 */
	public static String formatSql(String value) {
		if (value == null) {
			return value;
		} else {
			value = value.replace("'", "''");
			return trim(value);
		}
	}

	/**
	 * 从异常对象转换为字符串的详细信息
	 *
	 * @param e
	 *            Exception
	 * @return String
	 */
	public static String getExceptionInfo(Exception e) {
		StringWriter stringWriter = new StringWriter();
		PrintWriter printWriter = new PrintWriter(stringWriter);
		e.printStackTrace(printWriter);
		return stringWriter.toString();
	}

	/**
	 * 前补0
	 *
	 * @param number
	 * @param length
	 * @return
	 */
	public static String fillZero(int number, int length) {
		String numberString = String.valueOf(number);
		StringBuilder sb = new StringBuilder();
		int zeroLength = length - numberString.length();
		for (int i = 0; i < zeroLength; i++) {
			sb.append("0");
		}
		sb.append(numberString);
		return sb.toString();
	}

	/**
	 * 前补空格
	 *
	 * @param number
	 * @param length
	 * @return
	 */
	public static String fillSpace(String s, int length) {
		StringBuilder sb = new StringBuilder();
		int spaceLength = length - s.length();
		for (int i = 0; i < spaceLength; i++) {
			sb.append(" ");
		}
		sb.append(s);
		return sb.toString();
	}

	/**
	 * 前补指定字符
	 *
	 * @param s
	 * @param length
	 * @param fillStr
	 * @return
	 */
	public static String fillCharacter(String s, int length, String fillCharacter) {
		StringBuilder sb = new StringBuilder();
		int spaceLength = length - s.length();
		for (int i = 0; i < spaceLength; i++) {
			sb.append(fillCharacter);
		}
		sb.append(s);
		return sb.toString();
	}

	/**
	 * 后补空格
	 *
	 * @param number
	 * @param length
	 * @return
	 */
	public static String fillSpaceOnBehind(String s, int length) {
		StringBuilder sb = new StringBuilder();
		int spaceLength = length - s.length();
		sb.append(s);
		for (int i = 0; i < spaceLength; i++) {
			sb.append(" ");
		}
		return sb.toString();
	}

	/**
	 * 后补指定字符
	 *
	 * @param s
	 * @param length
	 * @param fillStr
	 * @return
	 */
	public static String fillCharacterOnBehind(String s, int length, String fillCharacter) {
		StringBuilder sb = new StringBuilder();
		int spaceLength = length - s.length();
		sb.append(s);
		for (int i = 0; i < spaceLength; i++) {
			sb.append(fillCharacter);
		}
		return sb.toString();
	}

	/**
	 * 获取字节异或结果
	 *
	 * @param array
	 * @return
	 */
	public static byte getXOR(byte[] array) {
		byte result = 0;
		for (int i = 0; i < array.length; i++) {
			if (i > 0) {
				result ^= array[i];
			} else {
				result = array[i];
			}
		}
		return result;
	}

	/**
	 * 获取字节异或结果（可排除后subtract位）
	 *
	 * @param array
	 * @param subtract
	 * @return
	 */
	public static byte getXOR(byte[] array, int subtract) {
		byte result = 0;
		for (int i = 0; i < array.length - subtract; i++) {
			if (i > 0) {
				result ^= array[i];
			} else {
				result = array[i];
			}
		}
		return result;
	}

	// 将byte数组转换成16进制的形式
	public static String getHexString(byte[] bytes) {
		String rtn = "";
		for (byte b : bytes) {
			String hex = Integer.toHexString(b & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			rtn += hex.toUpperCase();
		}
		return rtn;
	}

	/**
	 * 转换Object到Map<String,String>
	 *
	 * @param bean
	 * @return map
	 */
	public static Map<String, String> beanToMap(Object bean) {
		Map<String, String> map = new HashMap<String, String>();
		Class<?> obj = bean.getClass();
		Field[] fields = obj.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			fields[i].setAccessible(true);
			try {
				String value = fields[i].get(bean) == null ? "" : fields[i].get(bean).toString();
				map.put(fields[i].getName().toString(), value);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
		/*
		 * try { props = Introspector.getBeanInfo(bean.getClass(), Object.class)
		 * .getPropertyDescriptors(); if (props != null) { for (int i = 0; i <
		 * props.length; i++) { try{ String key = props[i].getName(); Object
		 * value = props[i].getReadMethod().invoke(bean);
		 * System.out.println(i+" - "+key); map.put(key, value.toString());
		 * }catch(Exception e){ continue; } } } } catch (Exception e) {
		 * e.printStackTrace(); return null; }
		 */
		return map;
	}

	/**
	 * 生成参数字符串
	 *
	 * @return 模式为key=value&key=value
	 */
	public static String generateParamStrByMap(Map<String, String> params) {
		// 塞入列表
		List<String> paramList = new ArrayList<String>();
		for (String key : params.keySet()) {
			String val = params.get(key);
			paramList.add(key + "=" + val);
		}

		// 防护
		if (paramList.size() == 0) {
			return null;
		}

		// 对列表进行排序
		Collections.sort(paramList);

		// 以&符分割拼装成字符串
		StringBuilder sb = new StringBuilder();
		sb.append(paramList.get(0));
		for (int i = 1; i < paramList.size(); i++) {
			sb.append("&").append(paramList.get(i));
		}
		return sb.toString();
	}

	/**
	 * JSONObject 转换成 Map
	 *
	 * @param json
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, String> jsonObjectToMap(JSONObject json) {
		Map<String, String> map = new HashMap<String, String>();
		Iterator it = json.keys();
		while (it.hasNext()) {
			String key = it.next().toString();
			String value = json.getString(key);
			map.put(key, value);

		}
		return map;
	}

	/**
	 * 获得动物字符画
	 *
	 * @param animalName
	 * @return
	 */
	public static String getAnimalDraw(String animalName) {
		String drow = "";
		if (animalName.equals("DOG")) {
			drow += "       .-~~~~-." + "\n";
			drow += "      / __     \\" + "\n";
			drow += "     | /  \\  /  `~~~~~-." + "\n";
			drow += "     ||    |  0         @" + "\n";
			drow += "     ||    |  _.        |" + "\n";
			drow += "     \\|    |   \\       /" + "\n";
			drow += "      \\    /  /`~~~~~~`" + "\n";
			drow += "      ('--'\"\"`)" + "\n";
			drow += "      /`\"\"\"\"\"`\\" + "\n";
		} else if (animalName.equals("CAT")) {
			drow += "  .-. __ _ .-." + "\n";
			drow += "  |  `  / \\  |" + "\n";
			drow += "  /     '.()--\\" + "\n";
			drow += " |         '._/" + "\n";
			drow += "_| O   _   O |_" + "\n";
			drow += "=\\    '-'    /=" + "\n";
			drow += "  '-._____.-'" + "\n";
		} else if (animalName.equals("JOECOOL")) {
			drow += "         .----." + "\n";
			drow += "      _.'__    `. " + "\n";
			drow += "  .--(#)(##)---/#\\" + "\n";
			drow += ".' @          /###\\" + "\n";
			drow += ":         ,   #####" + "\n";
			drow += " `-..__.-' _.-\\###/  " + "\n";
			drow += "       `;_:    `\"'" + "\n";
			drow += "     .'\"\"\"\"\"`. " + "\n";
			drow += "    /,  JOE  ,\\" + "\n";
			drow += "   //  COOL!  \\\\" + "\n";
			drow += "   `-._______.-'" + "\n";
			drow += "   ___`. | .'___ " + "\n";
			drow += "  (______|______)" + "\n";
		}
		return drow;
	}

	/**
	 * 人民币转成大写
	 *
	 * @param value
	 * @return String
	 */
	public static String hangeToBig(double value) {
		char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示
		char[] vunit = { '万', '亿' }; // 段名表示
		char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; // 数字表示
		long midVal = (long) (value * 100); // 转化成整形
		String valStr = String.valueOf(midVal); // 转化成字符串
		String head = valStr.substring(0, valStr.length() - 2); // 取整数部分
		String rail = valStr.substring(valStr.length() - 2); // 取小数部分
		String prefix = ""; // 整数部分转化的结果
		String suffix = ""; // 小数部分转化的结果
		// 处理小数点后面的数
		if (rail.equals("00")) { // 如果小数部分为0
			suffix = "整";
		} else {
			suffix = digit[rail.charAt(0) - '0'] + "角" + digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来
		}
		// 处理小数点前面的数
		char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组
		char zero = '0'; // 标志'0'表示出现过0
		byte zeroSerNum = 0; // 连续出现0的次数
		for (int i = 0; i < chDig.length; i++) { // 循环处理每个数字
			int idx = (chDig.length - i - 1) % 4; // 取段内位置
			int vidx = (chDig.length - i - 1) / 4; // 取段位置
			if (chDig[i] == '0') { // 如果当前字符是0
				zeroSerNum++; // 连续0次数递增
				if (zero == '0') { // 标志
					zero = digit[0];
				} else if (idx == 0 && vidx > 0 && zeroSerNum < 4) {
					prefix += vunit[vidx - 1];
					zero = '0';
				}
				continue;
			}
			zeroSerNum = 0; // 连续0次数清零
			if (zero != '0') { // 如果标志不为0,则加上,例如万,亿什么的
				prefix += zero;
				zero = '0';
			}
			prefix += digit[chDig[i] - '0']; // 转化该数字表示
			if (idx > 0)
				prefix += hunit[idx - 1];
			if (idx == 0 && vidx > 0) {
				prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿
			}
		}
		if (prefix.length() > 0)
			prefix += '圆'; // 如果整数部分存在,则有圆的字样
		return prefix + suffix; // 返回正确表示
	}

	/**
	 * 手机号码安全处理
	 *
	 * @param number
	 * @return
	 */
	public static String getSecretPhoneNo(String number) {
		if (!Formater.isNotEmpty(number)) {
			return number;
		}
		if (number.length() == 11) {
			number = number.substring(0, 3) + "****" + number.substring(7, 11);
		} else {
			number = "***********";
		}
		return number;
	}

	/**
	 * 身份证号码安全处理
	 *
	 * @param number
	 * @return
	 */
	public static String getSecretCredNo(String number) {
		if (!Formater.isNotEmpty(number)) {
			return number;
		}
		String ctr = "";
		if (number.length() == 15 || number.length() == 18) {
			for (int i = 0; i < number.length() - 10; i++) {
				ctr += "*";
			}
			number = number.substring(0, 8) + ctr + number.substring(number.length() - 2, number.length());
		} else {
			number = "***********";
		}
		return number;
	}

	/**
	 * 银行卡号安全处理
	 *
	 * @param number
	 * @return
	 */
	public static String getSecretCardNo(String number) {
		if (!Formater.isNotEmpty(number)) {
			return number;
		}
		if (number.length() >= 16) {
			number = "**** **** **** " + number.substring(number.length() - 4, number.length());
		} else {
			number = "**** **** **** ****";
		}
		return number;
	}

	/**
	 * 格式化银行卡号
	 *
	 * @param number
	 * @return
	 */
	public static String formatCardNo(String number) {
		if (!Formater.isNotEmpty(number)) {
			return number;
		}
		String formatNumber = "";
		for (int i = 1; i <= number.length(); i++) {
			formatNumber += number.substring(i - 1, i);
			if ((i != number.length()) && (i % 4) == 0) {
				formatNumber += " ";
			}
		}
		return formatNumber;
	}

	/**
	 * 日期判断
	 *
	 * @param dateStr
	 * @param formater
	 * @return
	 */
	public static boolean isDateString(String dateStr, String formater) {
		try {
			SimpleDateFormat format = new SimpleDateFormat(formater);
			format.setLenient(false);
			format.parse(dateStr);
			return true;
		} catch (Exception ex) {
			return false;
		}
	}
}
